package com.oweight.sagacious.payment.domain.service.spring;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.oweight.sagacious.api.model.msg.Message;
import com.oweight.sagacious.common.context.BaseContextHandler;
import com.oweight.sagacious.payment.domain.entity.AliPayProperties;
import com.oweight.sagacious.payment.domain.model.AliPayRefundModel;
import com.oweight.sagacious.payment.domain.model.AliPayUnifiedOrder;
import com.oweight.sagacious.payment.domain.service.IAliPayManager;
import com.oweight.sagacious.payment.domain.service.IAliPayPropertiesManager;
import com.oweight.sagacious.payment.infrastructure.alipay.AliPayApi;
import com.oweight.sagacious.payment.infrastructure.alipay.AliPayApiConfig;
import com.oweight.sagacious.payment.infrastructure.alipay.AliPayApiConfigKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 支付宝统一下单：领域服务实现
 *
 * @author SAGE
 * @version v1 2019-11-15 11:48:09
 */
@Slf4j
@Service
public class AliPayManager implements IAliPayManager {

    @Autowired
    IAliPayPropertiesManager aliPayPropertiesManager;

    AliPayApiConfig apiConfig = AliPayApiConfig.builder();

    /**
     * 设置支付宝配置
     *
     * @return
     */
    private AliPayApiConfig apiConfigBuilder() throws Exception {

        // todo 需要加缓存！
        String payPropertiesId = String.valueOf(BaseContextHandler.get("ali_pay_config_id"));
        AliPayProperties aliPayProperties = aliPayPropertiesManager.getByFdId(payPropertiesId);

        if (aliPayProperties == null) {
            log.error("支付宝付款：没有找到支付配置！");
            throw new Exception("支付宝付款：没有找到支付配置！");
        }

        BeanUtil.copyProperties(aliPayProperties, apiConfig, CopyOptions.create().ignoreNullValue().ignoreError());

//        apiConfig.setAppId("2019120769679657");
//        apiConfig.setAliPayPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAA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JDYVEORwqwRb2xjy5MPpNiZbc9ZSDRJwoEZkpbjbVJA4ueIlp0Ol9iCqQKBgQDZcsKELkmdNGLnCdkgBgVKAXLxKr7ChkQlz+caGJehqrZn6tHewtqX6SojvPTqWRJSmmRVwFcQqkTZpt7hiKQJ+B/uWGQ5Gm/92coMenCkW1k0hBAvQkjPr9fPmNvnL/4GylXIdA5WqcD8Km9jSGX0x9G5n4ezeR3zlKjugi6H9wKBgQCa8avhukaWnALnFWpdBYmMak2dw94tQW6n2AV1oX/f7AFNGh35Ta0td+l8TQqL3AUEK0ptlJGPoaYtJqcJbp6jZ3r/YH1QqnPws5vwr0vFh8/pNaDl/S6HJF4nEfdLBTod6kuO9w66UTeNDEmclcjcZ6i1EW2wy3zQTqrCdl+X7wKBgQCxEnrEGM1pbtd7PNHK+hwkf7mSGjTtQ1kLUZnn7k7MH7AaP2ZX+GT5f64JHD5098Or8H30NoSv1Xfrpa+qCRNL6vpVpTU4Kwc3uLqIHszLinfCBCkJ0vhn59HeA6RPRw2difcBHUDv4Zx9vDCosLQV+QIYHojq5Z42VMCcOPabUQKBgBegLA5CQgsrBMJJoKtIcd3IQ8d/mzwZUw8iwEpccswpB1XDWrit4G8jbqW2dZo31Uf6deHZmoxlIJqX3zZv+J5/4+BWzSTkqMMWD/wWLp6TA9/SfpMzFMokgHrCoYt944u2Mwk8oLFGOws1yW+n4zXAVJgvbSNdE84LgLwgIplfAoGBAJLIWPYPTO5xUhTCVlHkvgnVfjkElsAfKfiRapf1pEJGRd/krVwsnZXC2djJ8/STXjZGyd0Mv1E6snAwR4Sx775F+6BTkASFZ/+HSlF05oz49lsWtZjOgx1DfRsHl/CHiWJf3csOqSnsggCf3guTiXt6erMH0Cq2gN8WD/PM0AHm");
//        apiConfig.setAppAuthToken("201912BBed03ef02af1946efb29ce5eab2686X37");

        return apiConfig;
    }

    @Override
    public Message appOrder(AliPayUnifiedOrder order) {
        Message message = new Message();

        try {
            AliPayApiConfigKit.putApiConfig(apiConfigBuilder().build());

            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody(order.getBody());
            model.setSubject(order.getSubject());
            model.setOutTradeNo(order.getOutTradeNo());
            model.setTimeoutExpress("30m");
            model.setTotalAmount(order.getTotalAmount());
            model.setPassbackParams("callback params");

            String productCode = order.getProductCode();
            model.setProductCode(productCode);
            log.info("交易类型：" + productCode);

            String orderInfo = AliPayApi.appPayToResponse(model, order.getNotifyUrl()).getBody();

            log.info("支付宝付款：服务端下单成功！");

            message.ok("支付宝付款：服务端下单成功！");
            return message.data(orderInfo);

        } catch (Exception e) {
            log.error("支付宝付款失败！", e);
            return message.error("支付宝付款失败！" + e.getLocalizedMessage());
        }
    }

    @Override
    public Message order(AliPayUnifiedOrder order) {
        Message message = new Message();

        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setBody(order.getBody());
        model.setSubject(order.getSubject());
        model.setOutTradeNo(order.getOutTradeNo());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(order.getTotalAmount());

        String productCode = order.getProductCode();
        model.setProductCode(productCode);
        log.info("交易类型：" + productCode);

        String authCode = order.getAuthCode();
        if (StrUtil.isNotBlank(authCode)) {
            model.setAuthCode(authCode);
        }

        String body;
        try {

            AliPayApiConfigKit.putApiConfig(apiConfigBuilder().build());

            String notifyUrl = order.getNotifyUrl();
            String appAuthToken = apiConfig.getAppAuthToken();

            if (StrUtil.isNotBlank(appAuthToken)) {
                log.info("服务商模式");
                body = AliPayApi.tradePayToResponse(model, notifyUrl, appAuthToken).getBody();
            } else {
                log.info("普通模式");
                body = AliPayApi.tradePayToResponse(model, notifyUrl).getBody();
            }

        } catch (Exception e) {
            log.error("扫码付款失败！", e);
            return message.error("扫码付款失败！" + e.getLocalizedMessage());
        }

        return message.ok("扫码付款成功！").data(body);
    }

    @Override
    public Message sweepCodePayment() {
        return null;
    }

    @Override
    public Message refund(AliPayRefundModel model) {
        Message message = new Message();

        AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
        BeanUtil.copyProperties(model, alipayTradeRefundModel);


        try {
            AliPayApiConfigKit.putApiConfig(apiConfigBuilder().build());

            String appAuthToken = apiConfig.getAppAuthToken();
            String body = AliPayApi.tradeRefundToResponse(alipayTradeRefundModel, appAuthToken).getBody();

            log.info("服务器发起退款成功！");
            return message.ok("服务器发起退款成功！").data(body);

        } catch (Exception e) {
            log.error("退款失败！", e);
            return message.error("服务器发起退款失败！" + e.getLocalizedMessage());
        }

    }

}
